package Demo1_19;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User：Lenovo
 * Date:2025-01-19
 * Time:19:11
 */
class ListNode{
    int val;
    ListNode next;

    public ListNode(int val) {
        this.val = val;
    }
}
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA==null||headB==null){
            return null;
        }
        ListNode pl=headA;
        ListNode ps=headB;
        int lenA=0;
        while(pl!=null){
            lenA++;
            pl=pl.next;
        }
        int lenB=0;
        while(ps!=null)
        {
            lenB++;
            ps=ps.next;
        }
        pl=headA;
        ps=headB;
        int len=lenA-lenB;
        if(len<0){
            pl=headB;
            ps=headA;
            len=lenB-lenA;
        }
        while(len!=0){
            pl=pl.next;
            len--;
        }
        while(pl!=ps){
            pl=pl.next;
            ps=ps.next;
        }
        if(pl==null){
            return null;
        }
        return pl;
    }
    public static void main(String[] args) {
        // 创建第一个链表 1 -> 2 -> 3 -> 4 -> 5
        ListNode headA = new ListNode(1);
        ListNode node2A = new ListNode(2);
        ListNode node3A = new ListNode(3);
        ListNode node4A = new ListNode(4);
        ListNode node5A = new ListNode(5);
        headA.next = node2A;
        node2A.next = node3A;
        node3A.next = node4A;
        node4A.next = node5A;

        // 创建第二个链表 6 -> 7 -> 4 -> 5
        ListNode headB = new ListNode(6);
        ListNode node2B = new ListNode(7);
        headB.next = node2B;
        node2B.next = node4A; // 让第二个链表和第一个链表相交于节点 4

        Solution solution = new Solution();
        ListNode intersectionNode = solution.getIntersectionNode(headA, headB);
        if (intersectionNode!= null) {
            System.out.println("相交节点的值为: " + intersectionNode.val);
        } else {
            System.out.println("两个链表没有相交节点");
        }
    }
}
